<template>
  <div>
          <modal-header :left="`车辆列表`" right="查看定位轨迹" @back="close" />
          <div class="content-padding">
            <badge text="定位信息" />
            <a-row style="width: 900px">
              <a-col :span="24" style="margin-bottom: 12px">
                <div style="display: flex;align-items: center;font-size: 16px;font-weight: 500;">
                  <img style="width: 26px;height:18px;margin-right: 12px;" src="../../../assets/img/plateNo.png" alt="">
                  {{ plantNo || '-' }}
                </div>
              </a-col>
              <a-col :span="12" style="margin-bottom: 12px">
                <span class="title-label">最后位置：</span>
                {{ dataParams.address || "-" }}
              </a-col>
              <a-col :span="12" style="margin-bottom: 12px">
                <span class="title-label">最后时间：</span>
                {{ dataParams.addressTime || "-" }}
              </a-col>
              <a-col :span="12" style="margin-bottom: 12px">
                <span class="title-label">定位经度：</span>
                {{ dataParams.longitude || "-" }}
              </a-col>
              <a-col :span="12" style="margin-bottom: 12px">
                <span class="title-label">定位纬度：</span>
                {{ dataParams.latitude || "-" }}
              </a-col>
              <baidu-overlay></baidu-overlay>
              <a-col :span="24">
                <baidu-map class="bm-views" :ak="baiduAK" :center="positionMap.center" :zoom="13" scroll-wheel-zoom
                  @ready="positionMapHandle">
                  <!-- <baidu-overlay v-if="positionMap.lastMarker" pane="labelPane" :class="{ samples: true, active }"
                    @draw="draw">
                    <div class="sampless">{{ dataParams.address }}</div>
                    <img src="../../../assets/img/san.png" class="san_img" alt />
                  </baidu-overlay> -->
                  <baidu-marker v-if="positionMap.lastMarker" :position="positionMap.lastMarker" />
                </baidu-map>
              </a-col>
            </a-row>
          </div>
          <div>
            <div style="background-color: #f0f2f5; height: 12px"></div>

            <div class="content-padding">
              <badge text="轨迹信息" />

              <div class="flex_start">
                <a-range-picker :allowClear="false" format="YYYY-MM-DD HH:mm" :show-time="{
                  hideDisabledOptions: true,
                  defaultValue: [
                    moment('00:00', 'HH:mm'),
                    moment('23:59', 'HH:mm'),
                  ],
                  format: 'HH:mm',
                }" v-model="times" :placeholder="['开始时间', '结束时间']" @change="rangeTimeOkClick" />

                <div>
                  <a-button type="primary" style="margin-left: 12px" @click="rangeTimeOk('search')">查询</a-button>
                </div>
                <div>
                  <a-button style="margin-left: 12px" @click="rangeTimeOkReset">重置</a-button>
                </div>
                <div class="btn_small pointer" @click="thisMonth" style="margin-left: 12px">
                  本月
                </div>
                <div class="btn_small pointer" @click="lastMonth" style="margin-left: 12px">
                  上月
                </div>
              </div>
              <div class="flex_start text_content_bg" style="width: 736px">
                <img src="../../../assets/img/i.png" style="width: 18px; margin-right: 8px; margin-left: 12px" alt="" />
                <div class="text_content">请选择时间段进行轨迹查询</div>
              </div>
              <a-table :pagination="false" :locale="locale" :columns="grid.columns" :data-source="grid.data">
              </a-table>
              <div v-show="grid.total !== 0" style="text-align: right">
                <a-pagination show-size-changer :current="grid.queryParams.pageNum"
                  :pageSize="grid.queryParams.pageSize" @showSizeChange="onShowSizeChange" @change="onChange"
                  style="margin-top: 20px" size="small" :total="grid.total"
                  :show-total="(total) => `共${grid.total}条 `" />
              </div>
            </div>
            <a-modal title="查看轨迹详情" :footer="null" :visible="showDetail" @cancel="showDetail = false" :width="820"
              centered>
              <div style=" text-align: center; display: flex;justify-content: center;">
                <baidu-map v-if="hackReset" class="bm-view" :ak="baiduAK" :zoom="18" :center="locusMap.center"
                  scroll-wheel-zoom @ready="locusMapHandle">
                  <baidu-polyline :path="paths" stroke-color="blue" :stroke-weight="6"></baidu-polyline>
                </baidu-map>
              </div>
            </a-modal>
          </div>
  </div>
</template>
<script>
import moment from 'moment'
import { mapState } from 'vuex'
import badge from '@/components/badge'
import BaiduMap from 'vue-baidu-map/components/map/Map.vue'
import BaiduMarker from 'vue-baidu-map/components/overlays/Marker.vue'
import BaiduOverlay from 'vue-baidu-map/components/overlays/Overlay.vue'
// import pictureListDrawer from './pictureListDrawer'
import BaiduPolyline from 'vue-baidu-map/components/overlays/Polyline.vue'
import CardFormMixin from '@/mixins/CardFormMixin'
import Empty from '@/components/Empty/Empty'
import modalHeader from '@/components/modal-header'
import {
  apiOrAdminGet
} from '@/services/car.js'
import { deviceLocation, deviceLocationList } from '@/services/deviceManament'
export default {
  components: {
    modalHeader,
    BaiduMap,
    badge,
    BaiduMarker,
    BaiduPolyline,
    BaiduOverlay
    // Pagination
  },
  watch: {
    paths: {
      handler () {
        this.hackReset = false
        this.$nextTick(() => {
          this.hackReset = true
        })
      }
    }
  },
  mixins: [CardFormMixin],
  computed: {
    ...mapState('setting', ['baiduAK']),
    name () {
      return this.modal.data?.name || ''
    },
    appearance () {
      return this.modal.data?.appearance || ''
    },
    batteryCode () {
      return this.modal.data?.batteryCode || ''
    },
    brand () {
      return this.modal.data?.brand || ''
    },
    electricBoxInfoName () {
      return this.modal.data?.electricBoxInfoName || ''
    },
    model () {
      return this.modal.data?.model || ''
    },
    lastUseDate () {
      return this.modal.data?.lastUseDate || ''
    },
    type () {
      return this.modal.data?.type || ''
    },
    createTime () {
      return this.modal.data?.createTime || ''
    },
    // status () {
    //   return getOptionLabel(batteryStatusOptions, this.modal.data?.status)
    // },
    lastDayNum () {
      return this.modal.data?.lastDayNum
    },

    nowElectricity () {
      return this.modal.data?.nowElectricity
    },
    positionLastTime () {
      return this.positionMap?.lastMarker?.addressTime || ''
    },
    address () {
      return this.positionMap?.lastMarker?.address || ''
    }
  },
  data () {
    return {
      paths: [],
      plantNo: null,
      moment,
      locale: {
        emptyText: <Empty />
      },
      data: {},
      dataParams: {

      },
      showDetail: false,
      hackReset: true,
      positionMap: {
        map: null,
        BMap: null,
        center: '上海',
        lastMarker: null
      },
      locusMap: {
        map: null,
        BMap: null,
        center: '上海',
        paths: []
      },
      times: [],
      grid: {
        load: false,
        total: 0,
        queryParams: {
          pageSize: 20,
          pageNum: 1
        },
        data: [],
        columns: [
          {
            title: '轨迹ID',
            dataIndex: 'id',
            key: 'id',
            ellipsis: true
          },

          {
            title: '开始位置',
            dataIndex: 'beginAddress',
            key: 'beginAddress',
            ellipsis: true
          },
          {
            title: '骑行开始时间',
            dataIndex: 'beginTime',
            key: 'beginTime',
            ellipsis: true
          },

          {
            title: '结束位置',
            dataIndex: 'endAddress',
            key: 'endAddress',
            ellipsis: true
          },
          {
            title: '骑行结束时间',
            dataIndex: 'endTime',
            key: 'endTime',
            ellipsis: true
          },
          {
            title: '骑行距离(km)',
            dataIndex: 'mileage',
            key: 'mileage '
          },
          {
            title: '操作',
            dataIndex: 'action',
            key: 'action ',
            customRender: (text, record) => <a onClick={() => this.Rowclick(record)}>查看轨迹</a>
          }
        ]
      }
    }
  },
  methods: {
    open (record) {
      // this.test()
      this.plantNo = record.licensePlateNo
      this.getLocationInfo(record.id)
      this.grid.queryParams.deviceNo = record.deviceNo
    },
    async getLocationInfo (id) {
      const res = await deviceLocation(id)
      if (res.isSuccess) {
        this.dataParams = res.data
        this.positionMap.center = {
          lng: res.data.longitude,
          lat: res.data.latitude
        }
        // const res = await realTimeStateGet(this.deviceNo)
        // if (res.isSuccess) {

        // this.params = res.data
        if (
          Object.prototype.toString.call(res.data.longitude) !==
          '[object Null]'
        ) {
          this.positionMap.lastMarker = {
            lng: res.data.longitude,
            lat: res.data.latitude
          }

          this.positionMap.map.panTo(
            new this.positionMap.BMap.Point(
              res.data.longitude,
              res.data.latitude
            )
          )
        }
      } else {
        // this.$message.newFun(res.msg, 'error', 3)
        this.$message.newFun('暂无最后定位', 'error', 3)
        this.positionMap.lastMarker = null
        this.dataParams = {}
      }
    },
    close () {
      this.$emit('close')
    },
    thisMonth () {
      this.times = [
        moment().startOf('month').format('YYYY-MM-DD HH:mm:ss'),
        moment().format('YYYY-MM-DD HH:mm:ss')
      ]
      this.rangeTimeOk('search')
    },
    lastMonth () {
      this.times = [
        moment()
          .subtract(1, 'months')
          .startOf('month')
          .format('YYYY-MM-DD HH:mm:ss'),
        moment()
          .subtract(1, 'months')
          .endOf('month')
          .format('YYYY-MM-DD HH:mm:ss')
      ]
      this.rangeTimeOk('search')
    },
    onChange (page, pageSize) {
      this.grid.queryParams.pageNum = page
      console.log(pageSize)
      this.adminAlarmDml()
    },
    onShowSizeChange (current, pageSize) {
      this.grid.queryParams.pageNum = 1
      this.grid.queryParams.pageSize = pageSize
      console.log(current)
      this.adminAlarmDml()
    },
    // test () {
    //   this.paths.push({ lng: 116.404, lat: 39.915 })
    //   this.locusMap.map.panTo(new this.locusMap.BMap.Point(116.404, 39.915))
    // },
    rangeTimeOkClick (value) {
      console.log(value)
      this.times = [
        value[0].format('YYYY-MM-DD HH:mm:ss'),
        value[1].format('YYYY-MM-DD HH:mm:ss')
      ]
    },
    rangeTimeOkReset () {
      this.grid.queryParams.pageNum = 1
      delete this.grid.queryParams.beginTime
      delete this.grid.queryParams.endTime
      this.grid.queryParams.pageSize = 20
      this.times = []
      // this.adminAlarmDml()
    },
    async rangeTimeOk (value) {
      if (value) {
        console.log(this.times)
        if (this.times.length === 2) {
          const params = JSON.parse(JSON.stringify(this.grid.queryParams))
          params.endTime = this.times[1]
          params.beginTime = this.times[0]
          this.grid.queryParams = JSON.parse(JSON.stringify(params))
          this.grid.queryParams.pageNum = 1
          this.grid.queryParams.pageSize = 20

          this.adminAlarmDml()
        } else {
          this.$message.newFun('请选择时间区间', 'error', 3)
        }
      }
    },
    async adminAlarmDml () {
      console.log(this.grid.queryParams)
      const res = await deviceLocationList(this.grid.queryParams)
      if (res.isSuccess) {
        // this.grid.pageNum = 1
        this.grid.data = res.data.records
        this.grid.total = res.data.total
        if (this.grid.total === 0) {
          this.$message.newFun('暂无轨迹记录', 'error', 3)
        }
      } else {
        this.$message.newFun(res.msg, 'error', 3)
        this.modal.load = false
      }
    },
    async apiOrAdminGet (params, pointTime, deviceNo) {
      this.showDetail = true
      console.log(params, pointTime)
      if (this.pointsId !== params) {
        const res = await apiOrAdminGet(params, deviceNo)
        if (res.isSuccess) {
          this.pointsId = params
          this.paths = []
          if (res.data.trailDetailList.length > 0) {
            res.data.trailDetailList.forEach((ele) => {
              this.paths.push({
                lng: ele.longitude,
                lat: ele.latitude
              })
            })
            const firstNode = this.paths[0]
            if (firstNode && firstNode.lng && firstNode.lat) {
              this.locusMap.map.panTo(
                new this.locusMap.BMap.Point(firstNode.lat, firstNode.lng)
              )
              this.locusMap.center = {
                lng: firstNode.lng,
                lat: firstNode.lat
              }
            } else {
              this.$message.newFun('暂无轨迹', 'error', 3)
              this.paths = []
              this.locusMap.map.panTo('上海')
            }
          } else {
            this.$message.newFun('暂无轨迹', 'error', 3)
            this.paths = []
            this.locusMap.map.panTo('上海')
          }
        } else {
          this.modal.load = false
        }
      }
    },
    locusMapHandle ({ BMap, map }) {
      this.locusMap.map = map
      this.locusMap.BMap = BMap
      this.locusMap.map.panTo('上海')
    },
    positionMapHandle ({ BMap, map }) {
      this.positionMap.map = map
      this.positionMap.BMap = BMap
      this.positionMap.map.panTo('上海')
    },
    Rowclick (record) {
      this.apiOrAdminGet(record.id, record.pointTime, record.deviceNo)
    }
  }
}
</script>
<style lang="less" scoped>
.text_content_bg {
  margin-top: 20px;
  margin-bottom: 20px;
  width: 880px;
  height: 36px;
  background: #f5f5f5;
  border-radius: 4px;
}
.btn_small {
  width: 44px;
  height: 28px;
  line-height: 28px;
  color: #053781;
  background: #ffffff;
  text-align: center;
  border: 1px solid #053781;
  font-size: 14px;
  border-radius: 2px;
}
.bm-view {
  width: 790px;
  height: 400px;
  position: relative;
}

.bm-views {
  width: 790px;
  height: 300px;
  position: relative;
}

</style>
